/*
 * GameServer.java
 *
 * Distributed Systems: Project 2
 *
 */

package unimelb.distSystems.communications;

import java.net.InetAddress;
import java.util.Properties;

import unimelb.distSystems.communications.CORBA.*;

import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

public class GameServer implements Runnable{
    //private String[] myArgs = {"-ORBInitialPort "+Configurations.port_number};

    private AccountManager accountManager;
    private RoomsManager roomsManager;
    private String address="";
    private int port_no=0;

    public GameServer(String address,int port_no) {
        accountManager = new AccountManager();
        roomsManager = new RoomsManager();
        
        this.address=address;
        this.port_no=port_no;
    }

    public void run(){
        try{
            // create and initialize the ORB
        	Properties props = new Properties();
            props.put("org.omg.CORBA.ORBInitialPort", port_no);
            props.put("org.omg.CORBA.ORBInitialHost", address);
            ORB orb = ORB.init(new String[]{}, props);
            
            // get reference to rootpoa & activate the POAManager
            POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
            rootpoa.the_POAManager().activate();
            // create servant and get the CORBA reference of it
            GameServiceImpl gameImpl = new GameServiceImpl(this);
            org.omg.CORBA.Object ref = rootpoa.servant_to_reference(gameImpl);
            GameService gameService = GameServiceHelper.narrow(ref);
            // get the root naming context and narrow it to the NamingContextExt object
            org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
            NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
            // bind the Object Reference in Naming
            NameComponent path[] = ncRef.to_name("CrashTestDummyGame");
            ncRef.rebind(path, gameService);
            
            // get the information about the local host name
            InetAddress addr = InetAddress.getLocalHost();
            
            // SET CALLBACK
            gameImpl.setORB(orb);
            System.out.println("Game server is up and running ("+addr.getHostAddress()+":"+port_no+")");


            // wait for invocations from clients
            orb.run();
        } catch (Exception e) {}
    }



    public AccountManager getAccountManager() {
        return accountManager;
    }

    public void setAccountManager(AccountManager manager) {
        accountManager = manager;
    }

    
    public RoomsManager getRoomsManager() {
        return roomsManager;
    }

    public void setRoomsManager(RoomsManager roomsManager) {
        this.roomsManager = roomsManager;
    }


}
